var ws = require("nodejs-websocket")
let conList = []
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {

    conList.push(conn)

    conn.on("text", function (str) {

        let tempParse = JSON.parse(str)

        switch (tempParse.type) {
            case 'watcher':
                handleWatcher(conn)

                conn.send(JSON.stringify({
                    type: 'backKey',
                    data: conn.key
                }))

                break
            case 'createOffer':
                handleOffer(tempParse.data)
                break
            case 'createAnswer':
                handleAnswer(tempParse.data, tempParse.key)
                break
            case 'candidateToB':
                candidateToB(tempParse.data)
                break
            case 'candidateToA':
                candidateToA(tempParse.data, tempParse.key)
                break
        }

    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(3030)


function handleOffer(data) {
    allSend(JSON.stringify({
        type: 'createAnswer',
        data: data
    }))
}

function handleAnswer(data, key) {

    allSend(JSON.stringify({
        type: 'backAnswer',
        data: data,
        key
    }))
}


function allSend(str) {
    try {
        conList.forEach(im => {
            im.send(str)
        })
    } catch (e) { }

}

function candidateToB(data) {
    allSend(JSON.stringify({
        type: 'candidateToB',
        data: data
    }))
}

function candidateToA(data, key) {
    allSend(JSON.stringify({
        type: 'candidateToA',
        data: data,
        key
    }))
}

function handleWatcher(conn){
    allSend(JSON.stringify({
        type: 'mainSendOffer',
        data: conn.key
    }))

}